﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace DusonFramework.UrlRewrite
{
    public class RewriteHttpModule : IHttpModule
    {
        /// <summary>
        /// 实现接口的 Init 方法
        /// </summary>
        /// <param name="app"></param>
        public void Init(HttpApplication app)
        {
            app.BeginRequest += new EventHandler(this.ModuleRewriter_BeginRequest);
        }

        /// <summary>
        /// 实现接口的 Dispose 方法
        /// </summary>
        public void Dispose() { }

        /// <summary>
        /// BeginRequest响应事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void ModuleRewriter_BeginRequest(object sender, EventArgs e)
        {
            HttpApplication app = (HttpApplication)sender;
            Rewrite(app.Request.Path, app);
        }

        /// <summary>
        /// URL重写
        /// </summary>
        /// <param name="requestedPath"></param>
        /// <param name="app"></param>
        protected void Rewrite(string requestedPath, HttpApplication app)
        {
            string urlstr = requestedPath.ToLower();
            string reqstr = string.Empty;
            HttpContext Context = app.Context;
            int pos = requestedPath.IndexOf('?');
            if (pos > 0)
            {
                urlstr = urlstr.Substring(0, pos);
                reqstr = requestedPath.Substring(pos);
            }

            SiteUrls site = new SiteUrls(null); // Todo:通过Config文件或其它方式初始化网址映射字典
            string newurl = site.GetValue(urlstr);
            if (newurl == null)
                return;
            else
                Context.RewritePath(newurl + reqstr);
        }
    }

}
